package org.example.ttms.controller;

import com.fasterxml.jackson.annotation.JsonIgnore;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.util.Callback;
import org.example.ttms.Main;
import org.example.ttms.customize.AddTicket;
import org.example.ttms.customize.Detail;
import org.example.ttms.customize.Pop_ups;
import org.example.ttms.customize.Window;
import org.example.ttms.entityClass.ticket.Ticket;
import org.example.ttms.entityClass.train.Route;
import org.example.ttms.entityClass.train.Trips;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;


public class AddTripsController {

    @FXML
    private StackPane stackPane;

    @FXML
    private TextField tripsIdTextField;

    @FXML
    private ChoiceBox<Integer> routeChoiceBox;

    @FXML
    private ChoiceBox<Integer> hourChoiceBox;

    @FXML
    private ChoiceBox<Integer> minuteChoiceBox;

    @FXML
    private ChoiceBox<Integer> hourChoiceBox2;

    @FXML
    private ChoiceBox<Integer> minuteChoiceBox2;

    @FXML
    private DatePicker datePicker;

    @FXML
    private Button addButton;

    @FXML
    private Button addTicketButton;

    @FXML
    private TableView<Route> tableView;

    @FXML
    private TableColumn<Route, Integer> routeIdTableColumn;

    @FXML
    private TableColumn<Route, String> startStationTableColumn;


    @FXML
    private TableColumn<Route, String> endStationTableColumn;

    @FXML
    private TableColumn<Route, Integer> stationNumTableColumn;

    @FXML
    private TableColumn<Route, Void> detailTableColumn;

    @FXML
    private Label label;

    @FXML
    private ChoiceBox<String> tripsChoiceBox;

    @JsonIgnore
    private AddTicket ticket;

    public static Date date;

    public void initialize(){
        Route route = new Route();
        Trips trips = new Trips();
        HashMap<Integer, Route> hashMap = route.obtainAllRoute();
        List<String> tripsIdList = trips.obtainAllTripsId();
        //车次choiceBox
        tripsChoiceBox.getItems().addAll(tripsIdList);
        //监控tripsChoiceBox
//        tripsChoiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
//            @Override
//            public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
//                if(newValue != null)
//                    tripsIdTextField.setText(newValue);
//            }
//        });
        tripsChoiceBox.valueProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue != null)
                tripsIdTextField.setText(newValue);
        });
        //监控tripsTextField
        tripsIdTextField.textProperty().addListener((observable, oldValue, newValue) -> {
            if(!newValue.equals(tripsChoiceBox.getValue()))
                tripsChoiceBox.setValue(null);
        });
        //路线choiceBox
        routeChoiceBox.getItems().addAll(hashMap.keySet());
        //时间choiceBox
        List<Integer> hourList = new ArrayList<>();
        for(int i = 0; i < 24; i++){
            hourList.add(i);
        }
        hourChoiceBox.getItems().addAll(hourList);
        hourChoiceBox2.getItems().addAll(hourList);
        List<Integer> minuteList = new ArrayList<>();
        for(int i = 0; i < 60; i++){
            minuteList.add(i);
        }
        minuteChoiceBox.getItems().addAll(minuteList);
        minuteChoiceBox2.getItems().addAll(minuteList);
        //表格TableView
        ObservableList<Route> observableList = FXCollections.observableArrayList(hashMap.values());
        routeIdTableColumn.setCellValueFactory(cellData -> cellData.getValue().routeIdProperty().asObject());
        startStationTableColumn.setCellValueFactory(cellData -> cellData.getValue().startStationProperty());
        endStationTableColumn.setCellValueFactory(cellData -> cellData.getValue().endStationProperty());
        stationNumTableColumn.setCellValueFactory(cellData -> cellData.getValue().stationNumProperty().asObject());
        detailTableColumn.setCellFactory(new Callback<TableColumn<Route, Void>, TableCell<Route, Void>>() {
            @Override
            public TableCell<Route, Void> call(TableColumn<Route, Void> routeVoidTableColumn) {
                return new TableCell<Route, Void>(){
                    private final Button detailButton = new Button("查看详情");
                    {
                        detailButton.setOnAction(e -> {
                            Detail detail = new Detail();
                            detail.routeDetailWindow(getTableView().getItems().get(getIndex()));
                        });
                    }
                    @Override
                    public void updateItem(Void item, boolean empty){
                        super.updateItem(item, empty);
                        if(empty){
                            setGraphic(null);
                        }
                        else{
                            setGraphic(detailButton);
                        }
                    }
                };
            }
        });
        label.setVisible(observableList.isEmpty());
        tableView.setItems(observableList);
    }
    @FXML
    void chickAdd(ActionEvent event) {
        //计算票数
        ticket = AddTicketController.ticket;
        if(!addTicketJudgement())
            return ;
        AddTicket.tripsId = tripsIdTextField.getText();
        //创建车次
        Trips trips = new Trips(tripsIdTextField.getText(), routeChoiceBox.getValue(),
                date, hourChoiceBox2.getValue()+"小时"+minuteChoiceBox2.getValue()+"分钟",
                ticket.getAllSeatNum());
        //储存车次
        trips.addTrips(trips);
        //给路线添加车次
        trips.routeAddTrips(trips.getRouteId(), trips.getTripsId());
        //重置车票数及价格
        AddTicketController.ticket = new AddTicket();
        //刷新页面
        stackPane.getChildren().clear();
        Main.jumpPage2(stackPane, "addTrips.fxml");
    }

    @FXML
    void chickAddTicket(ActionEvent event) {
        AddTicket window = new AddTicket();
        window.addTicketWindow();
    }

    //添加车票评判
    public boolean addTicketJudgement(){
        Pop_ups popUps = new Pop_ups();
        if(routeChoiceBox.getValue() == null){
            popUps.pop_ups3("未选择路线");
            return false;
        }
        if(!goTimeJudgement()){
            return false;
        }
        if(!tripsIdJudgement()){
            return false;
        }
        if(hourChoiceBox2.getValue() == null || minuteChoiceBox2.getValue() == null ||
        hourChoiceBox2.getValue() == 0 && minuteChoiceBox2.getValue() == 0){
            popUps.pop_ups3("未选择所需时间");
            return false;
        }
        if(ticket.getAllSeatNum() == 0){
            popUps.pop_ups3("票数为0,无法添加");
            return false;
        }
        if(ticket.getBusinessSeatNum() != 0 && ticket.getBusinessSeatPrice() == 0){
            popUps.pop_ups3("商务座车票未设置价格");
            return false;
        }
        if(ticket.getFirstSeatNum() != 0 && ticket.getFirstSeatPrice() == 0){
            popUps.pop_ups3("一等座车票未设置价格");
            return false;
        }
        if(ticket.getSecondSeatNum() != 0 && ticket.getSecondSeatPrice() == 0){
            popUps.pop_ups3("二等座车票未设置价格");
            return false;
        }
        popUps.pop_ups4("车次添加成功");
        return true;
    }
    //出发时间评判
    public boolean goTimeJudgement(){
        Pop_ups popUps = new Pop_ups();
        if(hourChoiceBox.getValue() == null || minuteChoiceBox.getValue() == null){
            popUps.pop_ups3("未选择出发时间");
            return false;
        }
        String dateString = datePicker.getValue()+" "+hourChoiceBox.getValue()+":"+minuteChoiceBox.getValue();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            date = format.parse(dateString);
            Date currentDate = new Date();
            //一周之后
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
//            calendar.add(Calendar.DAY_OF_MONTH, 3);
            Date lastWeekDate = calendar.getTime();
            if(date.before(lastWeekDate)){
                popUps.pop_ups3("出发时间过早,无法添加");
                return false;
            }
            //一个月之内
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(currentDate);
            calendar2.add(Calendar.MONTH, 1);
            Date lastMonthDate = calendar2.getTime();
            if(date.after(lastMonthDate)){
                popUps.pop_ups3("出发时间过晚,无法添加");
                return false;
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
    //车次判断
    public boolean tripsIdJudgement(){
        Pop_ups popUps = new Pop_ups();
        if(tripsIdTextField.getText().isEmpty()){
            popUps.pop_ups3("未输入车次号");
            return false;
        }
        Trips trips = new Trips();
        List<Trips> tripsList = trips.obtainAllTrips();

        for(Trips trips1 : tripsList) {
            if (trips1.getTripsId().equals(tripsIdTextField.getText())) {
                LocalDate localDate = trips1.getGoTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                LocalDate localDate2 = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                if (localDate.isEqual(localDate2)) {
                    popUps.pop_ups3("该车次今天已经添加路线");
                    return false;
                }
            }
        }
        return true;
    }
}
